<template>
  <div>
    <el-container style="height: 600px; border: 1px solid #eee">
      <el-aside width="600px">
        <div>
          <div
            style="margin-top: 20px"
            @dragover="dragover($event)"
            @drop="drop($event)"
          >
            <el-input
              v-bind:placeholder="basepath"
              :disabled="true"
              @dragenter="dragEnter($event)"
              @dragover="dragover($event)"
              @drop="drop($event)"
              style="width:100%;"
            >
              <template slot="prepend">当前工程目录:</template>
            </el-input>
          </div>
          <div style="margin-top: 20px">
            <el-input
              v-bind:placeholder="description"
              v-model="description"
              style="width:100%;"
            >
              <template slot="prepend">此次构建描述:</template>
            </el-input>
          </div>
          <div style="margin-top: 20px">
            <el-input
              v-bind:placeholder="version"
              v-model="version"
              style="width:100%;"
            >
              <template slot="prepend">构建版本号:</template>
            </el-input>
          </div>
          <div style="margin-top: 20px">
            <el-tag>服务器地址：</el-tag>
            <el-radio-group
              style="margin-left: 20px"
              v-model="ServerAddr"
              size="medium"
              @change="ServerAddrChangeHandler"
            >
              <el-radio
                label="仿真服"
                border
                checked
              >仿真服</el-radio>
              <el-radio
                label="正式服"
                border
              >正式服</el-radio>
            </el-radio-group>
          </div>
          <div style="margin-top: 20px">
            <el-tag>构建的平台：</el-tag>
            <el-radio-group
              style="margin-left: 20px"
              v-model="platform"
              size="medium"
              @change="PlatformChangeHandler"
            >
              <el-radio
                label="android"
                border
                checked
              >Android</el-radio>
              <el-radio
                label="ios"
                border
              >IOS</el-radio>
              <el-radio
                label="web-mobile"
                border
              >web-mobile</el-radio>
            </el-radio-group>
          </div>
          <div style="margin-top: 20px">
            <el-button
              type="primary"
              @click="buildManifest()"
            >生成manifest</el-button>
            <el-button
              type="primary"
              @click="checkManifest()"
            >检查manifest</el-button>
            <el-button
              type="primary"
              @click="build()"
            >构建</el-button>
            <el-button
              type="primary"
              @click="compress()"
            >h5压缩</el-button>
            <el-switch style="margin-top: 20px"
              v-model="isEnable"
              @change="EnableHttpServer"
              active-text="未开启HttpServer"
              inactive-text="开启HttpServer">
            </el-switch>
          </div>
          <el-card style="margin-top: 20px">
            <div id="qrcode"></div>
            <span >{{apkTime}}</span>
          </el-card>
          
        
        

        </div>
      </el-aside>
      <el-main>
        <div>
          <el-input
            type="textarea"
            id="textarea_id"
            :rows="26"
            placeholder="log"
            v-model="textarea"
            :disabled="true"
          ></el-input>
        </div>
      </el-main>
    </el-container>
  </div>
</template>


<script>
const { ipcRenderer } = require('electron')
export default {
  data() {
    return {
      basepath: '请拖拽工程目录到此',
      ServerAddr: '仿真服',
      platform: 'android',
      textarea: '构建log....',
      description: '描述信息',
      version: '1.0.0',
      isEnable: 'true',
      apkTime: ''
    }
  },
  created: function() {
    this.register()
  },
  methods: {
    ServerAddrChangeHandler(value) {
      console.log('改变之后的值是:' + value)
    },
    PlatformChangeHandler(value) {
      console.log('改变之后的值是:' + value)
    },
    getArgs() {
      return {
        ServerAddr: this.ServerAddr,
        description: this.description,
        platform: this.platform,
        basepath: this.basepath,
        version: this.version
      }
    },
    argsToText() {
      const obj = this.getArgs()
      let text = this.version + ' | '
      if (obj.ServerAddr === '正式服') {
        text = text + '正式服 | '
      } else {
        text = text + '仿真服 | '
      }
      if (obj.platform === 'android') {
        text = text + 'Android | '
      } else if (obj.platform === 'ios') {
        text = text + 'IOS | '
      } else if (obj.platform === 'web-mobile') {
        text = text + 'web-mobile | '
      }
      text = text + obj.basepath
      return text
    },
    register() {
      ipcRenderer.on('readConfigToRender', (event, arg) => {
        console.log('文件中读取到的配置', arg)
        this.ServerAddr = arg.ServerAddr
        this.platform = arg.platform
        this.basepath = arg.basepath
        this.description = arg.description
        this.version = arg.version
      })
      ipcRenderer.on('stdout', (event, message) => {
        // 业务处理
        this.textarea = this.textarea + message
        /* eslint-disable */
        var textarea = document.getElementById('textarea_id')
        textarea.scrollTop = textarea.scrollHeight;
      })
      ipcRenderer.on('stderr', (event, message) => {
        this.textarea = this.textarea + message
        setTimeout(() => {
          // this.loading.close()
          this.$notify.error({
            title: '错误',
            message: '构建失败，详细信息看控制台',
            duration: 0
          })
        }, 200)
      })
      ipcRenderer.on('shellClose', (event, message) => {
        // 业务处理
        // this.textarea = this.textarea + '\n执行完成...\n'
        setTimeout(() => {
          this.loading.close()
          this.$notify.info({
            title: '提示',
            message: '命令执行完成',
            duration: 3000
          })
        }, 200)
      })
      ipcRenderer.send('readConfigToRender', null)
    },
    drop(event) {
      event.preventDefault()
      console.log('drop')
      console.log(event)
      for (const f of event.dataTransfer.files) {
        console.log('File(s) you dragged here: ', f.path, f)
        this.basepath = f.path
      }
    },
    dragover(event) {
      event.preventDefault()
      console.log('dragover')
    },
    buildManifest() {
      // this.$notify({
      //   title: '消息',
      //   type: 'success',
      //   message: '生成Manifest成功',
      //   duration: 0
      // })
      ipcRenderer.send('StartBuildManifest', this.getArgs())
      this.loading = this.$loading({
        lock: false,
        text: '构建中，请等待。。。',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
    },
    checkManifest() {
      // this.$notify({
      //   title: '消息',
      //   type: 'success',
      //   message: '生成Manifest成功',
      //   duration: 0
      // })
      /* eslint-disable */

      var fs = require('fs')
      const result = fs.readFileSync(this.basepath + '/assets/resources/project.manifest', 'utf8')
      console.log(JSON.parse(result))
      const obj = JSON.parse(result)
      const content = '版本号：' + obj.version + ' URL:' + obj.packageUrl + '\n' + (() => {
        if (obj.packageUrl.indexOf('Release') > 0) {
          return '正式服热更地址'
        } else {
          return '仿真服热更地址'
        }
      })()
      this.$confirm(content, '查看Manifest', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
    },
    compress(){
      this.loading = this.$loading({
        lock: false,
        text: '搜索文件中。。。',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      ipcRenderer.send('compress', this.basepath+'/build/test/web-mobile')
    },
    EnableHttpServer(){
      var http = require('http');
      var fs = require('fs');
      var url = require('url');
      if(!this.isEnable && this.httpserver){
          this.httpserver.close()
          document.getElementById('qrcode').innerHTML = ''
          this.qrcode = null
          return
      }
      if(!this.qrcode){
        this.qrcode = new QRCode(document.getElementById('qrcode'), { 
          text: 'http://192.168.1.250:12138/', 
          width: 128, 
          height: 128, 
          colorDark : '#000000', 
          colorLight : '#ffffff', 
          correctLevel : QRCode.CorrectLevel.H 
        });
      }
      let apkPath = "/build/test/jsb-default/frameworks/runtime-src/proj.android-studio/app/build/outputs/apk/debug/poker-debug.apk"
      var filePath = this.basepath + apkPath
      console.log(filePath)
      var fileStat = fs.stat(filePath, (err, state)=>{
          if(!err){
            console.log(state)
            this.apkTime = "最新修改时间："+state.ctime.toLocaleDateString()+state.ctime.toLocaleTimeString()
          }else{
            console.log(err)
            
          }
          
      })
      // 创建服务器
      this.httpserver = http.createServer( function (request, response) {  
        // 解析请求，包括文件名
        var pathname = url.parse(request.url)
        console.warn(pathname)
        var fileStat = fs.stat(filePath, 
            function(err, stats){
                if(err) {
                    response.writeHead(404);
                    response.end();
                    return null;
                }
                console.log('state', stats)
                //TODO:Content-Type应该根据文件类型设置
                response.writeHead(200, {"Content-Type": "application/octet-stream", "Content-Length": stats.size, "Content-Disposition" : "attachment; filename=poker.apk"});
                //使用Stream
                var stream = fs.createReadStream(filePath);

                stream.on('data',function(chunk){
                    response.write(chunk);
                });

                stream.on('end',function(){
                    response.end();
                });

                stream.on('error',function(){
                    response.end();
                });
            }
        )
      }).listen(12138);
      
      // 控制台会输出以下信息
      console.log('Server running at http://192.168.1.250:12138/');
    },
    build() {
      // var content = '参数如下：' + this.argsToText()
      var fs = require('fs')
      const result = fs.readFileSync(this.basepath + '/assets/resources/project.manifest', 'utf8')
      console.log(JSON.parse(result))
      const obj = JSON.parse(result)
      const server = (() => {
        if (obj.packageUrl.indexOf('Release') > 0) {
          return '正式服'
        } else {
          return '仿真服'
        }
      })()
      let content = ''
      let content1
      if (obj.version === this.version && server === this.ServerAddr) {
        content = 'manifest与构建参数对应\n' + this.argsToText()
        content1 = 'success'
      } else {
        content = '请重新生成manifest,然后再进行构建'
        content1 = 'error'
      }
      this.$confirm(content, '检查构建参数与manifest', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: content1
      })
        .then(() => {
          if (content1 === 'error') {
            return
          }
          this.$message({
            type: 'success',
            message: '开始构建balabala...'
          })
          this.textarea = ''
          ipcRenderer.once('StartBuild-Response', (event, arg) => {
            console.error('开始构建了！！！') // prints "pong"
            let i = 0
            for (const key in arg) {
              if (arg.hasOwnProperty(key)) {
                const element = arg[key]
                i++
                this.$notify.info({
                  title: '消息',
                  message: element,
                  duration: 3000 + i * 1000,
                  offset: i * 70
                })
              }
            }
            this.loading = this.$loading({
              lock: false,
              text: '构建中，请等待。。。',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            })
          })

          ipcRenderer.send('StartBuild', this.getArgs())
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消构建'
          })
        })
    }
  }
}
</script>


<style>
.el-header,
.el-footer {
  background-color: #b3c0d1;
  color: #333;
  text-align: center;
  line-height: 60px;
}

.el-aside {
  background-color: rgb(233, 243, 233);
  color: #333;
  text-align: left;
  margin-left: 10px;
  height: 100%;
}

.el-main {
  background-color: #e9eef3;
  color: #333;
  text-align: center;
  line-height: 160px;
  margin-right: 10px;
}

body > .el-container {
  margin-bottom: 40px;
  height: 100%;
}

.el-container:nth-child(5) .el-aside,
.el-container:nth-child(6) .el-aside {
  line-height: 260px;
}

.el-container:nth-child(7) .el-aside {
  line-height: 320px;
}
</style>